package com.wanglin.reggie.controller;

import com.wanglin.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

/**
 * CommonController
 *
 * @author 王林
 * @version 1.0
 * @description
 * @date 2025/5/29 14:17
 * @projectName reggie_take_out
 * @package com.wanglin.reggie.controller
 * @className com.wanglin.reggie.controller.CommonController
 * @copyright Copyright 2020 Theofanis, Wang Lin All rights reserved.
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    //文件上传路径
    @Value("${reggie.path}")
    private String basePath;

    //文件上传下载
    //文件上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info(file.toString());
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成随机文件名
        String fileName = UUID.randomUUID().toString() + suffix;
        //创建一个目录
        File dir = new File(basePath);
        if (!dir.exists()) {
            //判断目录是否存在
            dir.mkdirs();
        }
        //将文件保存到指定位置
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    //文件下载
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        log.info(name);
        //通过输入流读取文件内容
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //设置响应头
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
